package io.rehuo.modules.app.service.impl;


import cn.hutool.core.lang.Assert;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.rehuo.common.exception.RRException;
import io.rehuo.common.utils.*;
import io.rehuo.modules.app.dao.UserDao;
import io.rehuo.modules.app.entity.LoginUser;
import io.rehuo.modules.app.entity.UserBankEntity;
import io.rehuo.modules.app.entity.UserEntity;
import io.rehuo.modules.app.entity.UserRelationEntity;
import io.rehuo.modules.app.form.*;
import io.rehuo.modules.app.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UserRelationService userRelationService;

    @Autowired
    private UserLogininforService asyncService;

    @Autowired
    private UserBankService userBankService;

    @Autowired
    private OperatorLogService operatorLogService;

    @Override
    public UserEntity queryByMobile(String mobile) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("user_phone", mobile));
    }

    @Override
    public UserEntity login(LoginForm form) {
        //判断用户验证码是否正确
        String rCode = redisUtils.get(form.getMobile());
        Assert.notNull(rCode, "Captcha đã hết hạn");
        if (!StringUtils.equals(form.getCode(),rCode)){
            throw new RRException("Lỗi mã xác minh");
        }
        HttpServletRequest request = ServletUtils.getRequest();
        final UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        String deviceType = request.getHeader("User-Agent");
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        UserEntity user = queryByMobile(form.getMobile());
        if (user == null) {
            user = new UserEntity();
            user.setCreateTime(new Date());
            user.setUserPhone(form.getMobile());
            user.setApplyMoney(form.getApplyMoney());
            user.setResource(browser);
            user.setChannel(form.getChannel());
            if (deviceType.contains("Android")) {
                user.setDeviceType("Android");
            }else if (deviceType.contains("iPhone")) {
                user.setDeviceType("IOS");
            }else{
                user.setDeviceType("Other");
            }
            baseMapper.insert(user);
        } else {
            if (!user.getApplyMoney().equals(form.getApplyMoney())) {
                user.setApplyMoney(form.getApplyMoney());
                baseMapper.updateById(user);
            }
        }
        asyncService.recordLogininfor(user.getUserId(), Constants.LOGIN_SUCCESS, "user.login.success", request);
        LoginUser loginUser = buildLoginUser(user);
        LoginHelper.loginByDevice(loginUser);
        return user;
    }

    /**
     * 构建登录用户
     */
    private LoginUser buildLoginUser(UserEntity user) {
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getUserId());
        loginUser.setUserName(user.getUserName());
        return loginUser;
    }


    /**
     * @author : shiguang
     * @description : (保存用户基础信息1)
     * @date : 2022/9/10 23:40
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserOne(UserOneFormEntity entity, UserEntity userEntity) {
        BeanCopyUtils.copy(entity, userEntity);
//        Date date = DateUtils.stringToDate(entity.getBirthday(), "yyyy-MM-dd");
//        userEntity.setBirthday(date);
        userEntity.setStatus("1");
        baseMapper.updateById(userEntity);
    }

    /**
     * No such property: code for class: Script1
     *
     * @return : No such property: code for class: Script1
     * @author : shiguang
     * @description : (保存用户基础信息2)
     * @date : 2022/9/11 22:02
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserTwo(UserTwoFormEntity entity, UserEntity userEntity) {
        BeanCopyUtils.copy(entity, userEntity);
        userEntity.setStatus("2");
        baseMapper.updateById(userEntity);

        //保存重要联系人
        List<UserRelationForm> userRelationList = entity.getUserRelationList();
        List<UserRelationEntity> userRelationEntityList = BeanCopyUtils.copyList(userRelationList, UserRelationEntity.class);
        for (UserRelationEntity userRelationEntity : userRelationEntityList) {
            userRelationEntity.setUserId(userEntity.getUserId());
            userRelationEntity.setCreateTime(new Date());
        }
        userRelationService.remove(new QueryWrapper<UserRelationEntity>().eq("user_id", userEntity.getUserId()));
        userRelationService.saveBatch(userRelationEntityList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserThree(UserThreeFormEntity entity, UserEntity userEntity) {
        BeanCopyUtils.copy(entity, userEntity);
        userEntity.setStatus("3");
        baseMapper.updateById(userEntity);
        //保存用户银行卡
        UserBankEntity bankEntity = BeanCopyUtils.copy(entity, UserBankEntity.class);
        bankEntity.setCreateTime(new Date());
        bankEntity.setUserId(userEntity.getUserId());
        //判断用户是否存在银行卡
        UserBankEntity userBankEntity = userBankService.getOne(new QueryWrapper<UserBankEntity>().eq("user_id", userEntity.getUserId()).eq("del_flag", "0"));
        if (userBankEntity != null && userBankEntity.getBankId().equals(bankEntity.getBankId())
                && userBankEntity.getBankNo().equals(bankEntity.getBankNo()) && userBankEntity.getBankName().equals(bankEntity.getBankName())) {

        } else if (userBankEntity != null) {
            userBankEntity.setBankName(bankEntity.getBankName());
            userBankEntity.setBankId(bankEntity.getBankId());
            userBankEntity.setBankNo(bankEntity.getBankNo());
            userBankEntity.setUpdateTime(new Date());
            userBankEntity.setSimpleName(bankEntity.getSimpleName());
            userBankService.updateById(userBankEntity);
        } else {
            bankEntity.setCreateTime(new Date());
            userBankEntity.setSimpleName(bankEntity.getSimpleName());
            userBankService.save(bankEntity);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserOperator(UserEntity userEntity) {
        baseMapper.updateUserOperatorStatusByUserId(userEntity.getUserId());
        //添加运营商记录
        operatorLogService.saveLog(userEntity);
    }

    private String checkMobile(String mobile) {
        if (!mobile.startsWith("0086")) {
            if (mobile.startsWith("86")) {
                return "00" + mobile;
            } else {
                return "0086" + mobile.substring(mobile.length() - 11, mobile.length());
            }
        }
        return mobile;
    }

}
